package cn.yto.print.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.MessageDigest;

public class MachineCodeUtil {

    public static void main(String[] args) {
        try {
            String machineCode = generateMachineCode();
            System.out.println("Machine Code: " + machineCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 使用 MD5 对硬件信息进行哈希处理并生成机器码
     */
    public static String generateMachineCode() throws Exception {
        String hardwareInfo = getHardwareInfo();
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] hashBytes = md.digest(hardwareInfo.getBytes());
        StringBuilder hexString = new StringBuilder();
        for (byte b : hashBytes) {
            hexString.append(String.format("%02x", b));
        }
        return hexString.toString();
    }

    /**
     * 获取硬件信息
     */
    public static String getHardwareInfo() throws Exception {
        String diskSerial = getCommandOutput("wmic diskdrive get serialnumber");
        String motherboardSerial = getCommandOutput("wmic baseboard get serialnumber");
        String cpuId = getCommandOutput("wmic cpu get processorid");
//        String memorySerial = getCommandOutput("wmic memorychip get serialnumber");
        return diskSerial + motherboardSerial + cpuId;
    }

    /**
     * 执行系统命令并返回输出
     */
    public static String getCommandOutput(String command) throws Exception {
        Process process = Runtime.getRuntime().exec(command);
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StringBuilder output = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            // 过滤掉空白行
            if (!line.trim().isEmpty()) {
                output.append(line).append("\n");
            }
        }
        reader.close();
        process.waitFor();
        return output.toString().trim().split("\n")[1].trim();
    }

}
